package com.weixingtu.commuterCar.dao.impl;

import com.weixingtu.commuterCar.bean.Line;
import com.weixingtu.commuterCar.dao.LineDao;
import com.weixingtu.commuterCar.util.DruidUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class LineDaoImpl implements LineDao {
    @Override
    public void insert(Line line) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        String sql = "insert into line(lineId,lat,lng,speed,dateTime) values(?,?,?,?,?);";
        try {
            state = conn.prepareStatement(sql);
            state.setInt(1, line.getLineId());
            state.setDouble(2, line.getLat());
            state.setDouble(3, line.getLng());
            state.setDouble(4, line.getSpeed());
            state.setLong(5, line.getDateTime());
            state.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtil.close(conn, state, result);
        }
    }

    @Override
    public List<Line> queryLocation() {
        List<Line> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;

        String sql = " SELECT * FROM line ORDER BY obj_id DESC  LIMIT 0,4 ";
        try {
            state = conn.prepareStatement(sql);
            result = state.executeQuery();
            Line line = new Line();
            while (result.next()) {
                line.setLineId(result.getInt("lineId"));
                line.setLat(result.getDouble("lat"));
                line.setLng(result.getDouble("lng"));
                line.setSpeed(result.getDouble("speed"));
                line.setDateTime(result.getLong("dateTime"));

//                long dt = result.getLong("dateTime");
//                Date d = new Date(dt);
//                line.setDate(d);
//                System.out.println(line.getDate());

                data.add(line);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtil.close(conn, state, result);
        }
        return data;
    }

    @Override
    public boolean delAll() {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        int result = 0;

        String sql = " delete from line ";
        try {
            state = conn.prepareStatement(sql);
            result = state.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtil.close(conn, state, null);
        }
        return result != 0;
    }
}
